let count = 0;
const addBtn = document.getElementById('addBtn');
const addTr = document.getElementById('addTr');
const saveBtn = document.getElementById('save');

// 添加按钮点击事件
addBtn.addEventListener('click', function () {
    const rows = document.getElementsByTagName('tr');
    if (rows.length > 10) {
        return; // 限制接口次数
    }
    const newRow = document.createElement('tr');
    const cell1 = document.createElement('td');
    const input1 = document.createElement('input');
    input1.type = 'text';
    input1.id = `name_${count}`;
    input1.className = 'interface_name';
    input1.placeholder = `接口名称${count}`;
    cell1.appendChild(input1);

    const cell2 = document.createElement('td');
    const input2 = document.createElement('input');
    input2.type = 'text';
    input2.id = `url_${count}`;
    input2.className = 'interface_url';
    input2.placeholder = '请输入URL';
    cell2.appendChild(input2);

    const delBtn = document.createElement('button');
    delBtn.className = 'delApi';
    delBtn.id = `romeType_${count}`;
    delBtn.textContent = 'x';
    cell2.appendChild(delBtn);

    newRow.appendChild(cell1);
    newRow.appendChild(cell2);
    addTr.parentNode.insertBefore(newRow, addTr);

    delBtn.addEventListener('click', function () {
        const msg = document.getElementById('msg');
        if (msg) {
            msg.remove();
        }
        this.parentNode.parentNode.remove();
    });
    count++;
});

// 加载已经添加接口的列表
chrome.storage.sync.get(['api_data'], function (result) {
    if (typeof (result.api_data) === "undefined") {
        return;
    }
    const jsonData = JSON.parse(result.api_data);
    for (let i = 0; i < jsonData.length; i++) {
        const newRow = document.createElement('tr');
        const cell1 = document.createElement('td');
        const input1 = document.createElement('input');
        input1.type = 'text';
        input1.id = `name_${count}`;
        input1.className = 'interface_name';
        input1.placeholder = `接口名称${count}`;
        input1.value = jsonData[i].name;
        cell1.appendChild(input1);

        const cell2 = document.createElement('td');
        const input2 = document.createElement('input');
        input2.type = 'text';
        input2.id = `url_${count}`;
        input2.className = 'interface_url';
        input2.placeholder = '请输入URL';
        input2.value = jsonData[i].url;
        cell2.appendChild(input2);

        const delBtn = document.createElement('button');
        delBtn.className = 'delApi';
        delBtn.id = `romeType_${count}`;
        delBtn.textContent = 'x';
        cell2.appendChild(delBtn);

        newRow.appendChild(cell1);
        newRow.appendChild(cell2);
        addTr.parentNode.insertBefore(newRow, addTr);

        delBtn.addEventListener('click', function () {
            const msg = document.getElementById('msg');
            if (msg) {
                msg.remove();
            }
            this.parentNode.parentNode.remove();
        });
        count++;
    }
    console.log("=============== 加载添加接口列表完成 ====================");
});

// 表单去重
function distinct(arr) {
    const res = new Map();
    return arr.filter((a) => !res.has(a.name) && res.set(a.name, 1));
}

// 保存按钮点击事件
saveBtn.addEventListener('click', function () {
    const msg = document.getElementById('msg');
    if (msg) {
        msg.remove();
    }
    const arr = [];
    const arrAdd = [];
    // 假设 jsonApi 是全局变量，这里未定义，可根据实际情况修改
    for (let i = 0; i < jsonApi.length; i++) {
        arr.push({ name: jsonApi[i].name, url: jsonApi[i].url }); // 配置文件加载的;
    }
    // 获取表单数据,判断是否为空
    for (let num = 0; num < count; num++) {
        const nameInput = document.getElementById(`name_${num}`);
        const urlInput = document.getElementById(`url_${num}`);
        if (nameInput && urlInput) {
            const name = nameInput.value;
            const url = urlInput.value;
            if (name === "" || url === "") {
                const errorMsg = document.createElement('span');
                errorMsg.id = 'msg';
                errorMsg.style.color = 'red';
                errorMsg.style.marginLeft = '6px';
                errorMsg.style.fontSize = '10px';
                errorMsg.textContent = '表单不能为空';
                this.parentNode.insertBefore(errorMsg, this.nextSibling);
                return;
            }
            if (typeof (name) !== "undefined" && typeof (url) !== "undefined") {
                arrAdd.push({ name, url });
            }
        }
    }
    const arrList = arr.concat(arrAdd); // 合并数据
    const newArr = distinct(arrList); // 去重

    // 校验接口名称是否重复;
    if (newArr.length !== arrList.length) {
        const errorMsg = document.createElement('span');
        errorMsg.id = 'msg';
        errorMsg.style.color = 'red';
        errorMsg.style.marginLeft = '6px';
        errorMsg.style.fontSize = '10px';
        errorMsg.textContent = '接口名称不能重复';
        this.parentNode.insertBefore(errorMsg, this.nextSibling);
        return;
    }
    // 校验选中的接口是否存在;
    const interfaceSelect = document.getElementById('interface');
    if (interfaceSelect) {
        const name = interfaceSelect.options[interfaceSelect.selectedIndex].text;
        let flag = 0; // 不存在
        newArr.forEach(item => {
            if (item.name === name) {
                flag = 1; // 存在
            }
        });
        if (flag !== 1) {
            const errorMsg = document.createElement('span');
            errorMsg.id = 'msg';
            errorMsg.style.color = 'red';
            errorMsg.style.marginLeft = '6px';
            errorMsg.style.fontSize = '10px';
            errorMsg.textContent = '失败,企图删除默认接口';
            this.parentNode.insertBefore(errorMsg, this.nextSibling);
            return;
        }
    }
    const defaultOpen = document.querySelector('input[name="Fruit"]:checked');
    let defaultApi = {};
    if (interfaceSelect) {
        defaultApi = {
            name: interfaceSelect.options[interfaceSelect.selectedIndex].text.trim(),
            url: interfaceSelect.value
        };
    }

    // 存默认选中的接口
    chrome.storage.sync.set({ "default_api": defaultApi });
    // 存默认选中的窗体
    if (defaultOpen) {
        chrome.storage.sync.set({ "default_open": defaultOpen.value });
    }

    if (arrAdd.length > 0) {
        chrome.storage.sync.set({ "api_data": JSON.stringify(arrAdd) }); // 将新添加的数据放入内存
    } else {
        chrome.storage.sync.remove("api_data");
    }
    const successMsg = document.createElement('span');
    successMsg.id = 'msg';
    successMsg.style.color = 'green';
    successMsg.style.marginLeft = '6px';
    successMsg.style.fontSize = '10px';
    successMsg.textContent = '保存成功';
    this.parentNode.insertBefore(successMsg, this.nextSibling);
    // 假设 init 函数是全局函数，这里未定义，可根据实际情况修改
    init(); 
});